/**
 * HMI 批量删除数据管理 Composable
 *
 * 提供表格数据的获取、格式化、分页等功能
 * 使用统一的错误处理机制，确保用户体验一致性
 *
 * @param config 表格配置对象
 * @returns 数据管理相关的状态和方法
 */
import { ref, computed, reactive } from "vue";
import type {
  HmiBatchDeleteRow,
  HmiBatchDeleteConfig,
  HmiBatchDeleteQueryParams,
} from "@/api/hmi/hmi-batch-delete.api";
import { useHmiBatchDeleteStore } from "@/store/modules/hmi/hmi-batch-delete.store";
import { CommonHmiDataAPI } from "@/api/hmi/common-hmi-data.api";
import { useBaseTableData } from "@/components/HmiCommon/composables/useBaseTableData";
import { useErrorHandler } from "@/composables/useErrorHandler";

/**
 * 数据管理 Composable
 */
export function useHmiBatchDeleteData(config: HmiBatchDeleteConfig) {
  const hmiBatchDeleteStore = useHmiBatchDeleteStore();

  const base = useBaseTableData<HmiBatchDeleteRow>({
    apiPath: computed(() => config.apiPath),
    pageSize: computed(() => config.pagination?.pageSize || 10),
    group: computed(() => (config as any).group),
    orderByKey: computed(() => (config as any).orderByKey),
    formatRow: (item, index) => ({ ...(item as any), _index: index }),
  });

  const selectedRows = ref<HmiBatchDeleteRow[]>([]);
  const hasData = computed(() => base.tableData.value.length > 0);
  const currentPage = computed({
    get: () => Math.floor(base.pagination.offset / base.pagination.limit) + 1,
    set: (value) => {
      base.pagination.offset = (value - 1) * base.pagination.limit;
    },
  });

  const selectedIds = computed(() => selectedRows.value.map((row) => row[config.idKey]));

  function handleSelectionChange(selection: HmiBatchDeleteRow[]) {
    selectedRows.value = selection;
  }

  async function handlePageSizeChange(pageSize: number) {
    base.pagination.limit = pageSize;
    base.pagination.offset = 0;
    return await base.handlePaginationChange();
  }

  async function handleCurrentPageChange(page: number) {
    currentPage.value = page;
    return await base.handlePaginationChange();
  }

  return {
    // 状态
    tableData: base.tableData,
    total: base.total,
    selectedRows,
    selectedIds,
    pagination: base.pagination,
    loading: base.loading,
    hasData,
    currentPage,

    // 方法
    fetchData: base.fetchData,
    refreshData: base.refreshData,
    handleSelectionChange,
    handlePaginationChange: base.handlePaginationChange,
    handlePageSizeChange,
    handleCurrentPageChange,
  };
}

/**
 * 批量删除业务逻辑 Composable
 */
export function useHmiBatchDeleteOperations(config: HmiBatchDeleteConfig) {
  const hmiBatchDeleteStore = useHmiBatchDeleteStore();
  const { withErrorHandling } = useErrorHandler();

  // 批量删除
  async function batchDelete(ids: number[]) {
    if (!ids.length) {
      throw new Error("请选择要删除的数据");
    }

    const deleteKey = config.deleteKey || "index";
    const data = {
      [deleteKey]: ids,
    };

    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.batchDelete(config.apiPath, data);
    }, "批量删除");
  }

  // 批量重置
  async function batchReset(ids: number[]) {
    if (!ids.length) {
      throw new Error("请选择要重置的数据");
    }

    const deleteKey = config.deleteKey || "index";
    const data = {
      [deleteKey]: ids,
    };

    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.batchReset(config.apiPath, data);
    }, "批量重置");
  }

  // 批量传动
  async function batchTrans(rows: HmiBatchDeleteRow[]) {
    if (!rows.length) {
      throw new Error("请选择要传动的数据");
    }

    if (!config.transApi) {
      throw new Error("传动API未配置");
    }

    const transData = rows
      .map((row) => {
        const transBody: Record<string, any> = {};

        // 根据配置的 key 提取行数据
        (config.updateBodyKey || []).forEach((key) => {
          if (row[key] !== undefined) {
            transBody[key.toLowerCase()] = row[key];
          }
        });

        // 合并配置的固定值
        return {
          ...transBody,
          ...(config.updateBodyConfig || {}),
        };
      })
      .filter(Boolean);

    if (transData.length === 0) {
      throw new Error("没有有效的传动数据");
    }

    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.batchTrans(config.transApi!, transData);
    }, "批量传动");
  }

  // 批量对点
  async function batchPoint(rows: HmiBatchDeleteRow[]) {
    if (!rows.length) {
      throw new Error("请选择要传动的数据");
    }
    // post 的 api 为  config.apiPath;
    config.apiPath;
    // post 的 body 为 [{"index":1, "status": 1}, {}]

    const point_body = rows.map((row) => {
      const status = row.status === "×" ? 1 : 0;
      return {
        [config.idKey]: row.index,
        [config.updateValueKey!]: status,
      };
    });

    if (point_body.length === 0) {
      throw new Error("没有有效的传动数据");
    }

    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.batchPoint(config.apiPath!, point_body);
    }, "批量对点");
  }

  // 自动对点
  async function autoPoint() {
    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.autoPoint(config.autoPointApi!);
    }, "自动对点");
  }

  // 单行删除
  async function deleteRow(id: number) {
    const deleteKey = config.deleteKey || "index";
    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.deleteRow(config.apiPath, id, deleteKey);
    }, "删除数据");
  }

  // 单行重置
  async function resetRow(id: number) {
    const deleteKey = config.deleteKey || "index";
    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.resetRow(config.apiPath, id, deleteKey);
    }, "重置数据");
  }

  // 单行传动
  async function transRow(row: HmiBatchDeleteRow) {
    if (!config.transApi) {
      throw new Error("传动API未配置");
    }

    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.transRow(
        config.transApi!,
        row,
        config.updateBodyKey || [],
        config.updateBodyConfig || {}
      );
    }, "传动数据");
  }

  // 下载数据
  async function downloadData(id: number) {
    return await withErrorHandling(async () => {
      return await hmiBatchDeleteStore.downloadData(config.apiPath, id);
    }, "下载数据");
  }

  return {
    batchDelete,
    batchReset,
    batchTrans,
    batchPoint,
    autoPoint,
    deleteRow,
    resetRow,
    transRow,
    downloadData,
  };
}
